﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using ueEngine.Web.WebLogic.Model;
using ueEngine.Biz.Core.AppService.Member;
using ueEngine.Biz.Inf.LogicEntity;
using ueEngine.Biz.Core.AppService.Recruitment;
using ueEngine.Framework.Common;
using ueEngine.Web.WebLogic;

namespace ueEngine.Web.Controllers
{
    //[TraceBehavior]
    [ErrorHandle]
    [Compress]
    [Authorization(AuthorizeRole.User)]
    public class UserCenterController : Controller
    {
        //
        // GET: /UserCenter/

        public ActionResult Home()
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            return View();
        }
      
        #region 基本资料
        public ActionResult Info()
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="个人资料",
                    Link="/UserCenter/Info"
                }
            };
            var item = new UserService(HttpContext.User.Identity.Name).GetUser();
            InfoVModel model = new InfoVModel()
            {
                NickName = item.NickName,
                Location = item.Location,
                Phone = item.Phone,
                RealName = item.RealName,
                Sex = item.Sex == Gender.Male?"1":"0",
                Pass = true,
                Collage = item.Collage
            };
            ViewData["User"] = item;
            return View(model);
        }
        [HttpPost]
        public int Info(InfoVModel model)
        {
            var service = new UserService(HttpContext.User.Identity.Name);
            var user = service.GetUser();
            if (user == null)
            {
                return 0;
            }

            if (service.UpdateInfo(model.NickName, model.Location, model.Sex == "1" ? Gender.Male : Gender.Female,
                model.RealName,
                model.Phone,
                model.Collage)!= null)
            {
                //service.RemoveCacheOfUser();
                HttpContext.Session.Remove(HttpContext.User.Identity.Name);
                return 1;
            }
            return 0;
        }
        public ActionResult Individuation()
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="头像管理",
                    Link="/UserCenter/Individuation"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            return View();
        }
        [HttpPost]
        public int Individuation(string currentphoto)
        {
            var service = new UserService(HttpContext.User.Identity.Name);
            var user = service.GetUser();
            if (user == null)
            {
                return 0;
            }
            else
            {
                string file = currentphoto.Replace("/Temp/", "/Images/");
                file = GetNewName(Server.MapPath(file));
                try
                {
                    System.IO.File.Copy(Server.MapPath(currentphoto),
                      file, false);
                    System.IO.File.Delete(Server.MapPath(currentphoto));

                    user.Image = "/" + file.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "").Replace("\\", "/");
                    return service.UpdateImage(user.Image)!= null?1:0;// user.UpdateInfo(user.NickName, user.Location, user.Sex, user.RealName, user.Phone, user.Image) ? 1 : 0;
                }
                catch(Exception e)
                {
                    LogHelper.Write(CommonLogger.Zone, LogLevel.Error, e);
                    return 0;
                }
            }
        }
        private string GetNewName(string filePath, int circle = 1)
        {
            if (System.IO.File.Exists(filePath))
            {
                var fileInfo = new FileInfo(filePath);
                string name = fileInfo.Name;
                string newName = string.Empty;
                if (circle == 1) //如果是第一次递归
                {
                    newName = name.Substring(0, name.LastIndexOf('.')) + "(1)" + fileInfo.Extension;
                }
                else
                {
                    newName = name.Substring(0, name.LastIndexOf('(') + 1) + circle + ")" + fileInfo.Extension;
                }
                filePath = filePath.Replace(name, newName);
                filePath = GetNewName(filePath, ++circle);
            }
            return filePath;
        }       
        public string Upload(string id)
        {
            var files = System.Web.HttpContext.Current.Request.Files;
            if (files.Count > 0)
            {
                var uploadName = files.Keys[0];
                var item = new FileMonitor(String.Empty).Upload(
                    new UploadFileSetting()
                    {
                        BasePath = "/Customer/Temp",
                        TypeFilter = new List<FileType>() { 
                            FileType.jpg,
                            FileType.png
                        }
                    },
                    new List<UpLoadFileItem>() { 
                        new UpLoadFileItem(){
                            CopyMode= CopyMode.rename,
                            CustomerFileName=string.Empty,
                            File=System.Web.HttpContext.Current.Request.Files["Filedata"],
                            FileControlName="Filedata"
                        }
                    });
                return "{'result':'" + (item["Filedata"].IsSuccess ? 1 : 0) +
                    "','err':'" + item["Filedata"].Error +
                    "',svepath:'" + item["Filedata"].ServerPath + "'}";
            }
            return "{'result':'0','err':'不存在任何上次文件',svepath:''}"; ;
        }
        #endregion

        #region 账号安全
        public ActionResult Security()
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="安全设置",
                    Link="/UserCenter/Security"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();//.User.Entry().Member;
            return View(new SecurityVModel());
        }
        [HttpPost]
        public int Security(SecurityVModel model)
        {
            var service = new UserService(HttpContext.User.Identity.Name);
            var user = service.GetUser();
             if (user == null || model.Confirm != model.NewPassword)
             {
                 return 0;
             }
             else
             {
                 return service.ChangePassword(model.OldPassword, model.NewPassword) != null ? 1 : 0;
             }
        }
        #endregion 

        #region 我的简历
        public ActionResult Resumes(int page=0)
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="我的简历",
                    Link="/UserCenter/Resumes"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            ViewData["Resumes"] = new RecruitService(HttpContext.User.Identity.Name).QueryOfResumes(page, 20);
            return View();
        }
        public ActionResult NewResume()
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="添加新简历",
                    Link="/UserCenter/NewResume"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            return View(new NewResumeVModel());
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult NewResume(NewResumeVModel model)
        {
            model.Experience = Server.HtmlEncode(model.Experience);
            model.AboutMe = Server.HtmlEncode(model.AboutMe);
            model.EMail = HttpContext.User.Identity.Name;
            if (new RecruitService(HttpContext.User.Identity.Name).NewResume
                (new ResumeSheetModel()
                {
                    AboutMe = model.AboutMe,
                    Age = model.Age,
                    ContactPhone = model.Contact,
                    Experience = model.Experience,
                    Gender = model.Sex == "1" ? Gender.Male : Gender.Female,
                    RealName = model.RealName,
                    Status = (SocialRole)model.Status,
                    Title = model.Title,
                    UserName = HttpContext.User.Identity.Name,
                    Address=model.Address,
                    Email=model.EMail,
                    Area=model.Area,
                    College = model.College,
                    Degree= (Degree)model.Degree
                }) != null)
            {
                return Redirect("/UserCenter/Resumes");
            }
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="添加新简历",
                    Link="/UserCenter/NewResume"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            model.Pass = false;
            model.FaildMessage = "保存失败。请稍后再试";
            return View(model);
        }

        public ActionResult MyResume(int id)
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="我的简历",
                    Link="/UserCenter/MyResume"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            var item = new RecruitService(HttpContext.User.Identity.Name).GetResume(id);
            if (item.UserName != HttpContext.User.Identity.Name)
            {
                return Redirect("/UserCenter/Home");
            }
            ViewData["Id"] = id;
            return View(new NewResumeVModel()
            {
                AboutMe = item.AboutMe,
                Age = item.Age,
                Contact = item.ContactPhone,
                Experience = item.Experience,
                RealName = item.RealName,
                Sex = item.Gender == Gender.Male ? "1" : "0",
                Status = (int)item.Status,
                Title = item.Title,
                Address=item.Address,
                Area=item.Area,
                EMail=item.Email,
                College=item.College,
                Degree=(int)item.Degree
            });
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult MyResume(int id,NewResumeVModel model)
        {
            model.Experience = Server.HtmlEncode(model.Experience);
            model.AboutMe = Server.HtmlEncode(model.AboutMe);
            model.EMail = HttpContext.User.Identity.Name;
            var item = new RecruitService(HttpContext.User.Identity.Name).UpdateResume(
                new ResumeSheetModel()
                 {
                     Id = id,
                     AboutMe = model.AboutMe,
                     Age = model.Age,
                     ContactPhone = model.Contact,
                     Experience = model.Experience,
                     Gender = model.Sex == "1" ? Gender.Male : Gender.Female,
                     RealName = model.RealName,
                     Status = (SocialRole)model.Status,
                     Title = model.Title,
                     UserName = HttpContext.User.Identity.Name,
                     Address=model.Address,
                     Area=model.Area,
                     Email=model.EMail,
                     College=model.College,
                     Degree= (Degree)model.Degree
                 });
           if (item == null)
           {
               model.Pass = false;
               model.FaildMessage = "保存失败，请稍后再试";
           }
           else
           {
               model.Pass = true;
               model.FaildMessage = "保存成功";
           }
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="我的简历",
                    Link="/UserCenter/MyResume"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            ViewData["Id"] = id;
            return View(model);
        }
        [HttpPost]
        public int DeleteResume(int id)
        {
            return new RecruitService(HttpContext.User.Identity.Name).DeleteResume(id) ? 1 : 0;
        }
        #endregion

        public ActionResult mymarttime(int page = 0)
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="我的兼职",
                    Link="/UserCenter/mymarttime"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            ViewData["Data"] = new RecruitService(HttpContext.User.Identity.Name).QueryOfRequest(page, 20);
            return View();
        }

        #region 推荐兼职
        public ActionResult recommend(int page = 0)
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="推荐兼职",
                    Link="/UserCenter/recommend"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            ViewData["Data"] = new RecruitService(HttpContext.User.Identity.Name).QueryRecruitment(page, 20, RecruitSheetType.NoDefine, RecruitSheetSubject.Recommand);
            return View();
        }
        #endregion

        #region 关注企业
        public ActionResult Collect(int page = 0)
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="我的关注",
                    Link="/UserCenter/collect"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            var data = new RecruitService(HttpContext.User.Identity.Name).QueryOfCollect(page, 10);
            ViewData["Data"] = data;
            return View();
        }
        public int deletecollect(int id)
        {
            return new RecruitService(HttpContext.User.Identity.Name).RemoveRecruiterCollect(id) ? 1 : 0;
        }
        public ActionResult corporation(string ag,int page = 0)
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="会员中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="我的关注",
                    Link="/UserCenter/collect"
                }
            };
            ag = EncodeByBase64.Decode(ag);
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            ViewData["corp"] = new FirmService(ag).GetCorporation();
            return View();
        }
        #endregion

        #region 客服支付
        public ActionResult ConstomerServcie()
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="企业中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="客服与咨询",
                    Link="/UserCenter/constomerservcie"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            return View();
        }
        public ActionResult Suggestion()
        {
            ViewData["UserCenterSiteMap"] = new List<UserCenterSiteMapVModel>() { 
                new UserCenterSiteMapVModel()
                {
                    DisplayName="企业中心",
                    Link="/UserCenter/Home"
                },
                new UserCenterSiteMapVModel()
                {
                    DisplayName="客服与咨询",
                    Link="/UserCenter/suggestion"
                }
            };
            ViewData["User"] = new UserService(HttpContext.User.Identity.Name).GetUser();
            return View();
        }
        #endregion
    }
}
